<?php
// +----------------------------------------------------------------------
// | 产品类别管理模型
// +----------------------------------------------------------------------

namespace Admins\Model;

use Common\Model\Model;

class CategoryModel extends  Model{

    //array(填充字段,填充内容,[填充条件,附加规则])
    protected $_auto = array(
        array('create_time', 'time', 1, 'function'),
    );


    /**
     * 添加栏目
     * @param $data 页面POST的数
     * @return boolean|error
     */
    public function addCategory($data) {
        if (empty($data)) {
            $this->error = '添加栏目数据不能为空！';
            return false;
        }
        //终极栏目设置
        if(!isset($data['child']) && empty($data['parentid'])){
            $data['child']=1;
        }else{
            $data['child']=0;
        }
        $data = $this->create($data, 1);
        if ($data) {
            //添加数据
            $cateid = $this->add($data);
            if ($cateid) {
                //更新附件状态
                if ($data['image']) {
                    //更新附件状态，把相关附件与类别相关联
                    service("Attachment")->api_update('', 'cateid-' . $cateid, 1);
                }
                return $cateid;
            } else {
                $this->error = '栏目添加失败！';
                return false;
            }
        } else {
            return false;
        }
    }

    /**
     * 编辑栏目
     * @param type $post 页面提交过来的数据
     * @return boolean
     */
    public function editCategory($data) {
        if (empty($data)) {
            $this->error = '添加栏目数据不能为空！';
            return false;
        }
        $cateid = $data['cateid'];
        //查询该栏目是否存在
        $info = $this->where(array('cateid' => $cateid))->find();
        if (empty($info)) {
            $this->error = '该栏目不存在！';
            return false;
        }
        if(empty($data['catename'])){
            $this->error = '栏目名称不能为空';
            return false;
        }
        unset($data['cateid'], $data['child']);

        $result = $this->create($data, 2);
        if ($result) {
            if($this->where(array("cateid" => $cateid))->save($data)!==false){
                if ($data['image']) {
                    //更新附件状态，把相关附件和文章进行管理
                    service("Attachment")->api_update('', 'cateid-' . $cateid, 1);
                }
            }
        } else {
            return false;
        }
        return true;
    }


    /**
     * 删除栏目，如果有子栏目，会删除对应的子目录
     * @param type $catid 可以是数组，可以是栏目id
     * @return boolean
     */
    public function deleteCateid($cateid){
        if (!$cateid) {
            return false;
        }
        $where = array();
        //取得子栏目
        if (is_array($cateid)) {
            $where['cateid'] = array("IN", $cateid);
            $catList = $this->where($where)->select();
            foreach ($catList as $cat) {
                //是否存在子栏目
                if ($cat['child']) {
                    $arrchildid = explode(",", $cat['arrchildid']);
                    unset($arrchildid[0]);
                    $cateid = array_merge($cateid, $arrchildid);
                }
            }
            $where['cateid'] = array("IN", $cateid);
        } else {
            $where['cateid'] = $cateid;
            $catInfo = $this->where($where)->find();
            //是否存在子栏目
            if ($catInfo['child']) {
                $arrchildid = explode(",", $catInfo['arrchildid']);
                unset($arrchildid[0]);
                $cateid = array_merge($arrchildid, array($cateid));
                $where['cateid'] = array("IN", $cateid);
            }
        }

        //检查是否存在数据，存在数据不执行删除
        if (is_array($cateid) && count($cateid)>1) {
            $this->error = '栏目删除失败,请先删除该栏目子栏目!';
            return false;
        }else{
            if (M('Items')->where(array("cateid" =>array('IN', $cateid)))->count()) {
                $this->error='栏目删除失败，错误原因可能是栏目下存在信息，无法删除！';
                return false;
            }
            $status = $this->where($where)->delete();
            //删除相应的附件
            if (false !== $status) {
                if (is_array($cateid)) {
                    foreach ($cateid as $cid) {
                        service("Attachment")->api_delete('cateid-' . $cid);
                    }
                } else {
                    service("Attachment")->api_delete('cateid-' . $cateid);
                }
                return true;
            } else {
                return false;
            }
        }
    }


    /**
     * 获取子栏目ID列表
     * @staticvar type $categorys 静态变量 栏目数据
     * @param type $catid 栏目id
     * @return string 返回栏目子列表，以逗号隔开
     */
    public function getArrchildid($cateid) {
        if (!$this->categorys) {
            $this->categorys = cache('Category');
        }
        $arrchildid = $cateid;
        if (is_array($this->categorys)) {
            foreach ($this->categorys as $id => $cat) {
                if ($cat['parentid'] && $id != $cateid && $cat['parentid'] == $cateid) {
                    $arrchildid .= ',' . $this->getArrchildid($id);
                }
            }
        }
        return $arrchildid;
    }

    /**
     * 获取父栏目ID列表
     * @param integer $catid              栏目ID
     * @param array $arrparentid          父目录ID
     * @param integer $n                  查找的层次
     */
    public function getArrparentid($cateid, $arrparentid = '', $n = 1) {
        if (empty($this->categorys)) {
            $this->categorys = cache('Category');
        }
        if ($n > 10 || !is_array($this->categorys) || !isset($this->categorys[$cateid])) {
            return false;
        }
        //获取当前栏目的上级栏目ID
        $parentid = $this->categorys[$cateid]['parentid'];
        //所有父ID
        $arrparentid = $arrparentid ? $parentid . ',' . $arrparentid : $parentid;
        if ($parentid) {
            $arrparentid = $this->getArrparentid($parentid, $arrparentid, ++$n);
        } else {
            $this->categorys[$cateid]['arrparentid'] = $arrparentid;
        }
        return $arrparentid;
    }

    /**
     * 自动添加到缓存,如果启用缓存请直接调用
     */
    public function Category_cache(){
        $data= M('Category')->field(array('cateid,parentid'))->where(array('status'=>true))->order('sort ASC')->select();
        $CategoryIds = array();
        foreach ($data as $r) {
            $CategoryIds[$r['cateid']] = array(
                'cateid' => $r['cateid'],
                'parentid' => $r['parentid'],
            );
        }
        cache('Category',$CategoryIds);
    }



    //获取数据
    public function getData(){
        $data= M('Category')->field(array('cateid,parentid'))->order('sort ASC')->select();
        $CategoryIds = array();
        foreach ($data as $r) {
            $CategoryIds[$r['cateid']] = array(
                'cateid' => $r['cateid'],
                'parentid' => $r['parentid'],
            );
        }
        return $CategoryIds;
    }


}
